﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace MicroMq.Core.Helper
{
    static class AssemblyHelper
    {
        public static List<Type> GetTypes<A>(Assembly assembly) where A : Attribute
        {
            return assembly.GetTypes()
                 .Where(a => a.GetCustomAttribute<A>() != null)
                 .ToList();
        }

        public static List<(MethodInfo, A)> GetMethods<A>(Type type) where A : Attribute
        {
            return type.GetMethods().Select(a => (a, a.GetCustomAttribute<A>()))
                 .Where(a => a.Item2 != null)
                 .ToList();
        }


        public static Action<byte[]> Proxy(IServiceProvider serviceProvider, MethodInfo methodInfo)
        {
            var service = serviceProvider.GetService(methodInfo.DeclaringType);
            var parameters = methodInfo.GetParameters();
            return bytes =>
            {
                object[] args = new object[parameters.Length];
                for (int i = 0; i < parameters.Length; i++)
                {
                    var parameter = parameters[i];
                    args[i] = MTP.Serialize.MTPSerialize.Deserialize(bytes, parameter.ParameterType);
                    break;
                }
                methodInfo.Invoke(service, args);
            };
        }
    }
}
